import {
  createChat,
  deleteChatApi,
  getChatMessageHistory,
  queryChatList,
  updateChatTitle,
} from '@/api/chat';
import { type ChatMessage, IChatInfo, type MessageAttachment } from '@/interface/chat';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useChatStore = defineStore('chat', () => {
  // 当前聊天ID
  const currentChatId = ref<string | number>('');

  // 聊天列表
  const chatList = ref<IChatInfo[]>([]);

  // 当前聊天
  const currentChat = ref<IChatInfo>({} as IChatInfo);

  // 消息队列
  const messages = ref<ChatMessage[]>([]);

  // 最新消息
  const latestMessage = computed(() => {
    return (currentChat.value as IChatInfo).messages &&
      (currentChat.value as IChatInfo).messages!.length > 0
      ? (currentChat.value as IChatInfo).messages![
          (currentChat.value as IChatInfo).messages!.length - 1
        ]
      : null;
  });

  // 附件队列
  const attachments = ref<MessageAttachment[]>([]);

  // 附件分组
  const groupMessageAttachmentsByType = (attachments: MessageAttachment[]) => {
    return attachments.reduce((acc, item) => {
      acc[item.type] = acc[item.type] || [];
      if (item.type === 'question') {
        // TODO: question类型特殊处理
        acc['question'] = item;
      } else {
        acc[item.type].push(item);
      }
      return acc;
    }, {} as Record<string, any>);
  };

  // 分组后的附件
  const attachmentsGroupedByType = computed(() => {
    return groupMessageAttachmentsByType(attachments.value);
  });

  // 初始化聊天
  const initChat = async () => {
    // messages.value = [
    //   {
    //     id: new Date().getTime(),
    //     role: 'assistant',
    //     content: '你好！我是AI助手，有什么可以帮助你的吗？',
    //     type: 'text',
    //     timestamp: new Date(),
    //   },
    //   // 示例附件消息
    //   // {
    //   //   id: new Date().getTime() + 1,
    //   //   role: 'user',
    //   //   content: '这里有一些文件需要处理',
    //   //   type: 'text',
    //   //   timestamp: new Date(),
    //   //   attachments: [
    //   //     {
    //   //       id: 'att-1',
    //   //       type: 'file',
    //   //       name: 'document.pdf',
    //   //       url: '/example.pdf',
    //   //       size: 1024000,
    //   //     },
    //   //     {
    //   //       id: 'att-2',
    //   //       type: 'image',
    //   //       name: 'screenshot.png',
    //   //       url: 'https://via.placeholder.com/300x200',
    //   //       size: 512000,
    //   //     },
    //   //   ],
    //   // },
    //   // {
    //   //   id: new Date().getTime() + 2,
    //   //   role: 'assistant',
    //   //   content: '我已经收到了你的文件，让我来帮你分析一下。',
    //   //   type: 'text',
    //   //   timestamp: new Date(),
    //   //   attachments: [
    //   //     {
    //   //       id: 'att-3',
    //   //       type: 'link',
    //   //       name: 'analysis-result',
    //   //       url: 'https://example.com/analysis',
    //   //       title: '文件分析结果',
    //   //       description: '这是对你上传文件的详细分析报告，包含了主要内容摘要和建议。',
    //   //     },
    //   //   ],
    //   // },
    // ];
    currentChatId.value = '';
    attachments.value = [];
    chatList.value = [];
    try {
      // 查询聊天列表
      await getChatList();
      setDefaultChat();
    } catch (error) {
      console.error('初始化聊天失败:', error);
      throw error; // 重新抛出错误，让调用方处理
    }
  };

  // 设置默认聊天
  const setDefaultChat = () => {
    if (chatList.value.length > 0) {
      switchChat(chatList.value[0].id); // 切换到第一个聊天
    } else {
      // 创建聊天
      createNewChat();
    }
  };

  // 创建聊天
  const createNewChat = async () => {
    try {
      const res = await createChat();
      console.log('🚀 ~ createChat ~ res:', res);
      chatList.value.unshift(
        new IChatInfo(res.data.conversation_id, res.data.title, new Date(), [])
      );
      await switchChat(res.data.conversation_id);
    } catch (error) {
      console.error('创建会话失败:', error);
      throw error; // 重新抛出错误，让调用方处理
    }
  };

  // 删除聊天
  const deleteChat = async (id: string | number) => {
    try {
      await deleteChatApi({ conversation_id: id });
      chatList.value = chatList.value.filter(item => item.id !== id);
      // 如果当前聊天ID是删除的会话ID，则设置默认聊天
      if (currentChatId.value === id) {
        setDefaultChat();
      }
    } catch (error) {
      console.error('删除会话失败:', error);
    }
  };

  // 查询聊天列表
  const getChatList = async () => {
    try {
      const { conversations } = await queryChatList();
      chatList.value = conversations.map(c => ({ ...c, messages: [] }));
      console.log('🚀 ~ getChatList ~ chatList.value:', chatList.value);
    } catch (error) {
      console.error('查询聊天列表失败:', error);
      // 查询失败时保持当前状态，不清空现有列表
      throw error; // 重新抛出错误，让调用方处理
    }
  };

  // 设置当前聊天ID
  const setCurrentChatId = (id: string | number) => {
    currentChatId.value = id;
    currentChat.value = chatList.value.find(item => item.id === id) ?? ({} as IChatInfo);
  };

  // 设置当前聊天记录（分页加载）
  const setCurrentChatMessage = async (
    id: string | number,
    page: number = 1,
    size: number = 10
  ) => {
    try {
      const res = await getChatMessageHistory({
        conversation_id: +id,
        page,
        size,
      });
      console.log('🚀 ~ setCurrentChatMessage ~ res:', res);

      const targetChat = chatList.value.find(item => item.id === id);
      if (targetChat) {
        const newMessages = res.messages.reverse();

        if (page === 1) {
          // 第一页直接替换
          targetChat.messages = newMessages;
        } else {
          // 后续页面追加到开头（历史消息在前）
          targetChat.messages = [...newMessages, ...(targetChat.messages || [])];
        }

        // 保存分页信息
        targetChat.pagination = {
          currentPage: page,
          pageSize: size,
          total: res.total || 0,
          hasMore: !(res.page === res.pages),
        };
      }
    } catch (error) {
      console.error('获取聊天消息历史失败:', error);
      // 获取失败时保持当前消息状态
      throw error; // 重新抛出错误，让调用方处理
    }
  };

  // 加载更多消息（分页加载）
  const loadMoreMessages = async (id: string | number) => {
    try {
      const targetChat = chatList.value.find(item => item.id === id);
      if (!targetChat || !targetChat.pagination?.hasMore) {
        console.log('没有更多消息可加载');
        return false;
      }

      const nextPage = targetChat.pagination.currentPage + 1;
      await setCurrentChatMessage(id, nextPage, targetChat.pagination.pageSize);
      return true;
    } catch (error) {
      console.error('加载更多消息失败:', error);
      throw error;
    }
  };

  // 切换聊天
  const switchChat = async (id: string | number) => {
    try {
      if (currentChatId.value === id) return;
      setCurrentChatId(id);
      if (
        (currentChat.value as IChatInfo)?.messages &&
        (currentChat.value as IChatInfo)?.messages?.length
      )
        return;
      await setCurrentChatMessage(id, 1, 10); // 默认加载第一页10条数据
    } catch (error) {
      console.error('切换聊天失败:', error);
      // 切换失败时保持当前状态
    }
  };

  // 清空当前聊天ID
  const clearCurrentChatId = () => {
    currentChatId.value = '';
  };

  // 添加附件
  const addMessageAttachment = (a: MessageAttachment) => {
    if (attachments.value.find(item => item.id === a.id)) return;
    attachments.value.push(a);
  };

  // 移除附件
  const removeMessageAttachment = (id: number) => {
    attachments.value = attachments.value.filter(item => +item.id !== +id);
  };

  // 清空附件
  const clearMessageAttachments = () => {
    attachments.value = [];
  };

  // 添加消息到队列（入队）
  const addMessage = (message: Omit<ChatMessage, 'id' | 'timestamp'>) => {
    const timestamp = Date.now();
    const newMessage: ChatMessage = {
      ...message,
      id: timestamp,
      timestamp: timestamp,
    };
    (currentChat.value as IChatInfo).messages?.push(newMessage);
    return newMessage;
  };

  // 移除消息（出队）
  const removeMessage = (messageId?: string) => {
    if (messageId) {
      const index = (currentChat.value as IChatInfo).messages?.findIndex(
        msg => msg.id! === +messageId || msg.timestamp === +messageId
      );
      if (index !== -1) {
        const removedMessage = (currentChat.value as IChatInfo).messages?.[index as number];
        (currentChat.value as IChatInfo).messages?.splice(index as number, 1);
        return removedMessage;
      }
      return null;
    } else {
      return (currentChat.value as IChatInfo).messages?.pop();
    }
  };

  // 清空所有消息
  const clearMessages = () => {
    (currentChat.value as IChatInfo).messages = [];
  };

  // 获取最新消息
  // const getLatestMessage = () => {
  //   return (
  //     (currentChat.value as IChatInfo).messages?.[
  //       (currentChat.value as IChatInfo).messages?.length - 1 ?? 0
  //     ] || null
  //   );
  // };

  // 获取消息数量
  const getMessageCount = () => {
    return (currentChat.value as IChatInfo).messages?.length || 0;
  };

  // 修改对话标题
  const changeChatTitle = async (title: string) => {
    await updateChatTitle({ conversation_id: currentChatId.value, title });
    currentChat.value.title = title;
  };

  return {
    // 状态
    currentChatId,
    chatList,
    messages: currentChat.value.messages,
    latestMessage,
    attachments,
    currentChat,
    attachmentsGroupedByType,
    // 方法
    initChat,
    createNewChat,
    getChatList,
    deleteChat,
    setCurrentChatId,
    clearCurrentChatId,
    loadMoreMessages,
    addMessageAttachment,
    removeMessageAttachment,
    clearMessageAttachments,
    addMessage,
    removeMessage,
    clearMessages,
    getMessageCount,
    switchChat,
    changeChatTitle,
    groupMessageAttachmentsByType,
  };
});
